package com.yushu.base.service.impl;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.yushu.authority.pojo.vo.PmUserVO;
import com.yushu.base.mapper.LogMapper;
import com.yushu.base.pojo.bo.Log;
import com.yushu.base.pojo.vo.LogVO;
import com.yushu.base.service.LogService;
import com.yushu.common.execption.CgException;
import com.yushu.common.shiro.ShiroUtil;
import com.yushu.common.util.date.DateUtils;
import com.yushu.common.util.pager.Pages;
import com.yushu.common.util.string.CamelCaseUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 
 * @author test
 * @CreateDate 2020-12-03 15:47:25
 */
@Service("logService")
public class LogServiceImpl extends ServiceImpl<LogMapper, Log> implements LogService {

    public Pages<LogVO> page(Pages<LogVO> page) {
        PmUserVO sessionUser = ShiroUtil.getSessionUser();
        EntityWrapper wrapper = new EntityWrapper<LogVO>();
        LogVO log = page.getData();
            if(null !=log) {
                if (StringUtils.isNotEmpty(log.getUserId())) {
                    wrapper.like("t.id", log.getUserId(), SqlLike.DEFAULT);
                }
                if (StringUtils.isNotEmpty(log.getUserId())) {
                    wrapper.like("t.user_id", log.getUserId(), SqlLike.DEFAULT);
                }
                if (StringUtils.isNotEmpty(log.getTitle())) {
                    wrapper.like("t.title", log.getTitle(), SqlLike.DEFAULT);
                }
                if (StringUtils.isNotEmpty(log.getUrl())) {
                    wrapper.like("t.url", log.getUrl(), SqlLike.DEFAULT);
                }
                if (StringUtils.isNotEmpty(log.getModuleId())) {
                    wrapper.like("t.module_id", log.getModuleId(), SqlLike.DEFAULT);
                }
                if (StringUtils.isNotEmpty(log.getTableId())) {
                    wrapper.like("t.table_id", log.getTableId(), SqlLike.DEFAULT);
                }
                if (StringUtils.isNotEmpty(log.getParams())) {
                    wrapper.like("t.params", log.getParams(), SqlLike.DEFAULT);
                }
                if (null != log.getCreateTimeBefore() && null != log.getCreateTimeAfter()) {
                    String dateBefore = DateUtils.dateToString(log.getCreateTimeBefore());
                    String dateAfter = DateUtils.dateToString(log.getCreateTimeAfter());
                    wrapper.between("t.create_time", dateBefore, dateAfter);
                }
                if (null != log.getExecutionTime()) {
                    wrapper.like("t.execution_time", log.getExecutionTime().toString(), SqlLike.DEFAULT);
                }
                if (StringUtils.isNotEmpty(log.getLgCountry())) {
                    wrapper.like("t.lg_country", log.getLgCountry(), SqlLike.DEFAULT);
                }
                if (StringUtils.isNotEmpty(log.getLgArea())) {
                    wrapper.like("t.lg_area", log.getLgArea(), SqlLike.DEFAULT);
                }
                if (StringUtils.isNotEmpty(log.getLgRegion())) {
                    wrapper.like("t.lg_region", log.getLgRegion(), SqlLike.DEFAULT);
                }
                if (StringUtils.isNotEmpty(log.getLgCity())) {
                    wrapper.like("t.lg_city", log.getLgCity(), SqlLike.DEFAULT);
                }
                if (StringUtils.isNotEmpty(log.getLgCounty())) {
                    wrapper.like("t.lg_county", log.getLgCounty(), SqlLike.DEFAULT);
                }
                if (StringUtils.isNotEmpty(log.getLgIsp())) {
                    wrapper.like("t.lg_isp", log.getLgIsp(), SqlLike.DEFAULT);
                }
                if (StringUtils.isNotEmpty(log.getLgAddress())) {
                    wrapper.like("t.lg_address", log.getLgAddress(), SqlLike.DEFAULT);
                }
                if (StringUtils.isNotEmpty(page.getSort())) {
                    wrapper.orderBy(CamelCaseUtil.toUnderlineName(page.getSort()), "asc".equals(page.getOrder()));
                }
            }
        List<LogVO> list = baseMapper.selectPageList(page, wrapper);
        page.setRecords(list);
        return page;
    }


    /**
     * 批量删除日志
     *
     * @param logs
     * @return
     */
    public boolean deleteBatch(List<Log> logs) throws CgException {
        boolean deleteState = false;
        try {
            List<String> ids = new ArrayList<String>();
            for (int i = 0; i < logs.size(); i++) {
                Log log = logs.get(i);
                ids.add(log.getId());
            }
            deleteState = deleteBatchIds(ids);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CgException(e.getMessage());
        }
        return deleteState;
    }


    /**
     * 通过主键更新日志的缓存数据
     *
     * @param log
     * @return
     */
    //@CachePut(value = "log", key = "#log.id")
    public Log updateByKey(Log log) throws CgException {
        try {
            PmUserVO sessionUser = ShiroUtil.getSessionUser();
            super.updateById(log);
        } catch (RuntimeException e) {
            //e.printStackTrace();
            throw new CgException(e.getMessage());
        }
        return log;
    }


    /**
     * 删除的时候同步日志的缓存数据
     *
     * @param id 主键
     * @return
     */
    //@CacheEvict(value = "log", key = "#id")
    @Override
    public boolean deleteById(Serializable id) {
        return super.deleteById(id);
    }

    /**
     * 保存的时候清除所有日志的缓存数据
     *
     * @param log
     * @return
     */
    //@CacheEvict(value = "log",allEntries=true)
    @Override
    public boolean insert(Log log) throws CgException {
        try {
            PmUserVO sessionUser = ShiroUtil.getSessionUser();
            log.setId(IdWorker.get32UUID());
            return super.insert(log);
        } catch (RuntimeException e) {
            throw new CgException(e.getMessage());
        }
    }

    /**
     * 查询时保存日志的缓存数据
     *
     * @param id 主键
     * @return
     */
    //@Cacheable(value = "log", key = "#id")
    @Override
    public Log selectById(Serializable id) {
        return super.selectById(id);
    }


    @Override
    public LogVO queryLogByKey(String id) {
        return baseMapper.queryLogByKey(id);
    }

    @Override
    public String checkRepeat(Map map) {
        String name = map.get("name") + "";
        String value = map.get("value") + "";
        String key = map.get("key") + "";
        int count = baseMapper.queryCountByName(map);
//        如果key存在，则是修改，否则是新增
        if (StringUtils.isNotBlank(key)) {
            /*如果是更新，则数字可以大于1*/
            if (count <= 0) {
                return "true";
            } else if (count > 1) {//说明存在多个
                return "false";
            } else if (count == 1) {
                EntityWrapper wrapper = new EntityWrapper<Log>();
                wrapper.eq(name, value);
                List<Log> logs = baseMapper.selectList(wrapper);
                String checkExit = "true";
                if (CollectionUtils.isNotEmpty(logs)) {
                    for (int i = 0; i < logs.size(); i++) {
                        Log log = logs.get(i);
//                        说明当前值象存在于不同的对象之中，也不能重复
                        if (!StringUtils.equals(log.getId().trim(), key.trim())) {
                            checkExit = "false";
                        }
                    }
                }
                return checkExit;
            } else {
                return "true";
            }
        } else {
            /*如果是新增，则数字可以大于0*/
            if (count > 1) {
                return "false";
            } else {
                return "true";
            }
        }
    }

    @Override
    public List<Log> selectList(Log log) {
        EntityWrapper wrapper = new EntityWrapper<Log>();

            if (StringUtils.isNotEmpty(log.getId())) {
                wrapper.eq("id", log.getId());
            }
            if (StringUtils.isNotEmpty(log.getUserId())) {
                wrapper.eq("user_id", log.getUserId());
            }
            if (StringUtils.isNotEmpty(log.getTitle())) {
                wrapper.eq("title", log.getTitle());
            }
            if (StringUtils.isNotEmpty(log.getUrl())) {
                wrapper.eq("url", log.getUrl());
            }
            if (StringUtils.isNotEmpty(log.getModuleId())) {
                wrapper.eq("module_id", log.getModuleId());
            }
            if (StringUtils.isNotEmpty(log.getTableId())) {
                wrapper.eq("table_id", log.getTableId());
            }
            if (StringUtils.isNotEmpty(log.getParams())) {
                wrapper.eq("params", log.getParams());
            }

            if (null != log.getExecutionTime()) {
                wrapper.eq("execution_time", log.getExecutionTime().toString());
            }
            if (StringUtils.isNotEmpty(log.getLgCountry())) {
                wrapper.eq("lg_country", log.getLgCountry());
            }
            if (StringUtils.isNotEmpty(log.getLgArea())) {
                wrapper.eq("lg_area", log.getLgArea());
            }
            if (StringUtils.isNotEmpty(log.getLgRegion())) {
                wrapper.eq("lg_region", log.getLgRegion());
            }
            if (StringUtils.isNotEmpty(log.getLgCity())) {
                wrapper.eq("lg_city", log.getLgCity());
            }
            if (StringUtils.isNotEmpty(log.getLgCounty())) {
                wrapper.eq("lg_county", log.getLgCounty());
            }
            if (StringUtils.isNotEmpty(log.getLgIsp())) {
                wrapper.eq("lg_isp", log.getLgIsp());
            }
            if (StringUtils.isNotEmpty(log.getLgAddress())) {
                wrapper.eq("lg_address", log.getLgAddress());
            }

        List<Log> list = selectList(wrapper);
        return list;
    }
}
